from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from django.utils import timezone
from .models import City, Datacenter, Host, PasswordHistory, HostStatistics
from .serializers import (
    CitySerializer, DatacenterSerializer, HostSerializer,
    PasswordHistorySerializer, HostStatisticsSerializer
)
from .utils import ping_host, generate_password
from .tasks import rotate_host_password


class CityViewSet(viewsets.ModelViewSet):
    queryset = City.objects.all()
    serializer_class = CitySerializer


class DatacenterViewSet(viewsets.ModelViewSet):
    queryset = Datacenter.objects.all()
    serializer_class = DatacenterSerializer

    def get_queryset(self):
        queryset = Datacenter.objects.all()
        city_id = self.request.query_params.get('city_id')
        if city_id:
            queryset = queryset.filter(city_id=city_id)
        return queryset


class HostViewSet(viewsets.ModelViewSet):
    queryset = Host.objects.all()
    serializer_class = HostSerializer

    def get_queryset(self):
        queryset = Host.objects.all()

        # 按数据中心过滤
        datacenter_id = self.request.query_params.get('datacenter_id')
        if datacenter_id:
            queryset = queryset.filter(datacenter_id=datacenter_id)

        # 按城市过滤
        city_id = self.request.query_params.get('city_id')
        if city_id:
            queryset = queryset.filter(datacenter__city_id=city_id)

        # 按状态过滤
        status = self.request.query_params.get('status')
        if status:
            queryset = queryset.filter(status=status)

        return queryset

    def perform_create(self, serializer):
        # 创建主机时，如果没有提供密码，则生成一个随机密码
        if not serializer.validated_data.get('root_password'):
            serializer.validated_data['root_password'] = generate_password()
        serializer.save()

    @action(detail=True, methods=['get'])
    def ping(self, request, pk=None):
        """检测主机是否可ping通"""
        host = self.get_object()
        result = ping_host(host.ip_address)

        if result:
            return Response({'status': 'success', 'message': f'主机 {host.hostname} ({host.ip_address}) 可以ping通'})
        else:
            return Response(
                {'status': 'error', 'message': f'主机 {host.hostname} ({host.ip_address}) 无法ping通'},
                status=status.HTTP_200_OK
            )

    @action(detail=True, methods=['post'])
    def rotate_password(self, request, pk=None):
        """手动触发密码轮换"""
        host = self.get_object()
        rotate_host_password.delay(host.id)
        return Response({'status': 'success', 'message': f'已触发主机 {host.hostname} 的密码轮换任务'})


class PasswordHistoryViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = PasswordHistory.objects.all()
    serializer_class = PasswordHistorySerializer

    def get_queryset(self):
        queryset = PasswordHistory.objects.all()

        # 按主机过滤
        host_id = self.request.query_params.get('host_id')
        if host_id:
            queryset = queryset.filter(host_id=host_id)

        # 按日期范围过滤
        start_date = self.request.query_params.get('start_date')
        end_date = self.request.query_params.get('end_date')

        if start_date:
            queryset = queryset.filter(changed_at__gte=start_date)
        if end_date:
            queryset = queryset.filter(changed_at__lte=end_date)

        return queryset


class HostStatisticsViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = HostStatistics.objects.all()
    serializer_class = HostStatisticsSerializer

    def get_queryset(self):
        queryset = HostStatistics.objects.all()

        # 按日期过滤
        date = self.request.query_params.get('date')
        if date:
            queryset = queryset.filter(date=date)

        # 按城市过滤
        city_id = self.request.query_params.get('city_id')
        if city_id:
            queryset = queryset.filter(city_id=city_id)

        # 按数据中心过滤
        datacenter_id = self.request.query_params.get('datacenter_id')
        if datacenter_id:
            queryset = queryset.filter(datacenter_id=datacenter_id)

        return queryset